<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class pro_laporan_perangkat extends MY_Controller {
	
	// Define Allowed Extension for File Upload
	var $arr_allowed_upload	= array('txt','jpg', 'jpeg', 'png', 'bmp', 'gif','ppt','pptx','xls','xlsx','doc','docx','pdf');
	
	function __construct()
	{
		parent::__construct(); 
		
		// Uses Model
		$this->load->model('pro_data_perangkat/sample_master_model', 'Master');
		// $this->load->model('pro_turnover/sample_reference_model', 'Ref');
		// $this->load->model('pro_turnover/sample_detail2_model', 'Detail2');
		// $this->load->model('pro_turnover/sample_detail_file_model', 'DetailFile');
		// $this->load->model('pro_turnover/combo_model', 'Combo');
		
		// Secure Page With Session
		$this->secure_session();
	}
	
	function index(){
		// Display Index
		$data['title'] = $this->session_menu_label;
		
		viewByTemplate('pro_laporan_perangkat/index', $data, 'grid');
	}
	
	function getdata()
	{
		// Ajax Response For Datagrid
		echo $this->Master->GetJSON();
	}
	
	function dtl_sample2_data()
	{
		// Ajax Response For Datagrid
		echo $this->Detail2->GetJSON(post('kode_barang'));
	}
	
	function dtl_sample_file_data()
	{
		// Ajax Response For Datagrid
		echo $this->DetailFile->GetJSON(post('pk_master'));
	}
	
	function create()
	{
		// Display Form Create
		$data['title'] = "Tambah Data Master";
		$data['data'] = NULL;
		
		// Define Combo Data
		$data['arr_reference']	= $this->Combo->SampleReference();
		$data['arr_province']	= $this->Combo->SWProvince();
		
		$data['mode'] = "create";
		viewByTemplate('pro_laporan_perangkat/form', $data, 'form');
	}

	function edit()
	{
		// Display Form Edit
		$data['title'] = "Ubah Data Master";
		$data['data'] = $this->Master->GetSingleView(get('kode_barang'));
		
		// Define Combo Data
		// $data['arr_reference']	= $this->Detail2->GetDivisi();
		//$data['drop_down']	= $this->Detail2->GetDivisi();
		// $data['arr_province']	= $this->Combo->SWProvince();
		
		$data['file_allowed']		= implode(', ', $this->arr_allowed_upload);
		
		$data['mode'] = "edit";
		viewByTemplate('pro_laporan_perangkat/form', $data, 'form');
	}
	
	function view()
	{
		// Display Form View
		$data['title'] = "View Data Master";
		$data['data'] = $this->Master->GetSingleView(get('pk_master'));
		
		// Define Combo Data
		$data['arr_reference']	= $this->Combo->SampleReference();
		$data['arr_province']	= $this->Combo->SWProvince();
		
		$data['file_allowed']		= implode(', ', $this->arr_allowed_upload);
		
		$data['mode'] = "view";
		viewByTemplate('pro_laporan_perangkat/form', $data, 'form');
	}
	
	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");


		// Validation
		if (post("kode_barang") == '') {
			$error->Add("pk_master", "Primary Key", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT COUNT(1) FROM sample_master WHERE UPPER(pk_master) = '".@strtoupper(@trim(post("pk_master")))."'")) > 0) {
			$error->Add("pk_master", "Primary Key", $tpl_duplicate);
		}
		
		return $error;
	}
	
	function ajax_post()
	{
		// Ajax Response For Submit Form
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";
		
		// Get Error Template
		$tpl_insert_success = $this->MessageTemplate("CS001");
		$tpl_update_success = $this->MessageTemplate("CS002");
		
		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{
				// Fill Post Data Array
				$data	= post_by_key(array('kode_barang','nama_barang','nama_merek','spesifikasi','tipe','harga','jumlah','keterangan'
											));

				// Set Primary Key Variable
				$data['pk_master']	= @strtoupper(@trim(post("kode_barang")));
				$pk_master	= $data['pk_master'];
				
				/* Set Date Format
				$data['field2']	= ($data['field2'] == '' ? NULL : date_format3($data['field2'], 'YYYY-MM-DD'));
				$data['field3']	= ($data['field3'] == '' ? NULL : date_format3($data['field3'], 'YYYY-MM-DD'));
				
				// Set Number Format
				$data['field4']	= (float)toNumber($data['field4']);
				$data['field5']	= (float)toNumber($data['field5']);*/
				
				if (post("mode") == "create")
				{
					$ls_genid	= $pk_master;
					
					$data['create_date']	= NOW;
					$data['create_id']		= USERID;
					
					$this->Master->Add($data);
					
					$ls_response = $tpl_insert_success['message_id'];
				}
				else if (post("mode") == "edit")
				{
					unset($data['pk_master']);
					
					//$data['modify_date']	= NOW;
					//$data['modify_id']		= USERID;
					
					$this->Master->Update(	$data, 
											array('kode_barang'	=> $pk_master));
					
					$ls_response = $tpl_update_success['message_id'];
				}
				
				// ----- >> Detail Sample 2
				$dtl_sample2	= $this->data['dtl_sample2'];
				$total_deleted	= $dtl_sample2['num_row']['deleted'];
				$total_inserted	= $dtl_sample2['num_row']['inserted'];
				$total_updated	= $dtl_sample2['num_row']['updated'];
				for($i=0,$max_i=$total_deleted; $i<$max_i; $i++){
					$row = $dtl_sample2['deleted'][$i];
					
					$this->Detail2->DeleteSingle($row['pk_master'], $row['index_no']);
				}
				for($i=0,$max_i=$total_inserted; $i<$max_i; $i++){
					$row = $dtl_sample2['inserted'][$i];
					
					$row['index_no']	= $this->get_data("SELECT NVL((SELECT MAX(index_no) FROM sample_detail2 WHERE pk_master = '".$pk_master."'),0)+1 seqid FROM DUAL");
					$row['jumlah']		= (float)$row['jumlah'];
					
					$row['pk_master'] = $pk_master;
					$row['create_date']	= NOW;
					$row['create_id']	= USERID;
					
					$this->Detail2->Add($row);
				}
				for($i=0,$max_i=$total_updated; $i<$max_i; $i++){
					$row = $dtl_sample2['updated'][$i];
					
					$index_no	= $row['index_no'];
					unset($row['index_no']);
					
					$row['jumlah']		= (float)$row['jumlah'];
					
					$row['modify_date']	= NOW;
					$row['modify_id']	= USERID;
				
					$this->Detail2->Update($row, array(	'pk_master'	=> $pk_master, 
														'index_no'	=> $index_no));
				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}
	
	function cetak(){
		$as_pk_master	= get('kode_barang');
		
		if($as_pk_master!='' && $as_pk_master!=''){
			
			// Load FPDF
			$this->load->helper('fpdf');
			
			// Set Data
			$data['data']			= $this->Master->GetSingleView($as_pk_master);
			//$data['arr_detail1']	= $this->Detail1->GetDetailByID($as_pk_master);
			//$data['arr_detail2']	= $this->Detail2->GetDetailByID($as_pk_master);
			
			// Load View
			$this->load->view('pro_laporan_perangkat/cetak', $data);
			
		}
	}

	function print_excel()
	{
		
		$x=0;

		$data_p = $this->Master->GetForExcel();

		$date = date('Y-m-d');

		//load our new PHPExcel library
		$this->load->library('excel');
		//activate worksheet number 1
		$this->excel->setActiveSheetIndex(0);
		//name the worksheet
		$this->excel->getActiveSheet()->setTitle("Laporan Perangkat_".$date);

		$no = 1;

			
		if ($data_p) {

			$styleArrayBorder = array(
				'borders' => array(
					'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN
					)
				)
			);

			$this->excel->getActiveSheet()->setCellValue('B8', 'NO');
			$this->excel->getActiveSheet()->setCellValue('C8', 'KODE BARANG');
			$this->excel->getActiveSheet()->setCellValue('D8', 'NAMA BARANG');
			$this->excel->getActiveSheet()->setCellValue('E8', 'NAMA MERK');
			$this->excel->getActiveSheet()->setCellValue('F8', 'SPESIFIKASI');
			$this->excel->getActiveSheet()->setCellValue('G8', 'KONDISI BARANG');
			$this->excel->getActiveSheet()->setCellValue('H8', 'TIPE');
			$this->excel->getActiveSheet()->setCellValue('I8', 'HARGA');
			$this->excel->getActiveSheet()->setCellValue('J8', 'JUMLAH');
			$this->excel->getActiveSheet()->setCellValue('K8', 'KETERANGAN');

			$this->excel->getActiveSheet()->getStyle('B8:K8')->getFont()->setBold(true);
			$this->excel->getActiveSheet()->getStyle('B8:K8')->getFill()->applyFromArray(array('type' => PHPExcel_Style_Fill::FILL_SOLID,'startcolor' => array('rgb' => 'EEEE11')));
			$this->excel->getActiveSheet()->getStyle('B8:K8')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

			$x = 8;

			for($i=0;$i<=$data_p['total']-1;$i++){
				$x++;

				$rows = $data_p['rows'];
				$rows2 = $rows[$i];

				$this->excel->getActiveSheet()->setCellValue('B'.$x, $no);
				$this->excel->getActiveSheet()->setCellValue('C'.$x, $rows2['kode_barang']);
				$this->excel->getActiveSheet()->setCellValue('D'.$x, $rows2['nama_barang']);
				$this->excel->getActiveSheet()->setCellValue('E'.$x, $rows2['nama_merek']);
				$this->excel->getActiveSheet()->setCellValue('F'.$x, $rows2['spesifikasi']);
				$this->excel->getActiveSheet()->setCellValue('G'.$x, $rows2['kondisi']);
				$this->excel->getActiveSheet()->setCellValue('H'.$x, $rows2['tipe']);
				$this->excel->getActiveSheet()->setCellValue('I'.$x, $rows2['harga']);
				$this->excel->getActiveSheet()->setCellValue('J'.$x, $rows2['jumlah']);
				$this->excel->getActiveSheet()->setCellValue('K'.$x, $rows2['keterangan']);

				$no++;
			}

			
		}

		$this->excel->getActiveSheet()->setCellValue('B4', strtoupper("Laporan Perangkat"));
		$this->excel->getActiveSheet()->setCellValue('B5', '('.$date.')');			

		$styleArray = array(
			'borders' => array(
			    'allborders' => array(
			    'style' => PHPExcel_Style_Border::BORDER_THIN
			    )
			),
			'font'  => array(
			    'size'  => 9,
			    'name'  => 'verdana'
			)
		);

		$this->excel->getActiveSheet()->getStyle('B8:K'.$x)->applyFromArray($styleArray);
		unset($styleArray);

		$styleArray1 = array(
		    'font'  => array(
		    'bold'  => true,
		    'uppercase' => true,
		    'size'  => 11,
		    'name'  => 'Calibri'
		    )
		);

		$this->excel->getActiveSheet()->getColumnDimension('C')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('D')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('G')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('I')->setWidth(22);
		$this->excel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
		$this->excel->getActiveSheet()->getColumnDimension('K')->setWidth(22);
		

		$this->excel->getActiveSheet()->getStyle('D1:K'.$this->excel->getActiveSheet()->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00'); 

		$this->excel->getActiveSheet()->getStyle('C1:C'.$this->excel->getActiveSheet()->getHighestRow())
    	->getAlignment()->setWrapText(true);
    	$this->excel->getActiveSheet()->getStyle('K1:K'.$this->excel->getActiveSheet()->getHighestRow())
    	->getAlignment()->setWrapText(true);

		//set aligment to center for that merged cell (A1 to D1)
		// $this->excel->getActiveSheet()->getStyle('B1:B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$this->excel->getActiveSheet()->getStyle('B4:B5')->getFont()->setBold(true);

		$filename= 'Laporan Perangkat_'.$date.'.xls'; //save our workbook as this file name
		header('Content-Type: application/vnd.ms-excel'); //mime type
		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		header('Cache-Control: max-age=0'); //no cache
			             
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as .XLSX Excel 2007 format
		$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save('php://output');
	}

}
?>